﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TranTekBE.Trac_Nghiem
{
    public partial class ThemCauHoi : PagePopUp
    {
        public Database database = new Database(TinyLib.GetConfigKey("ConnectionString2"));
        public int questionId = 0;
        DataTable question = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                questionId = int.Parse(Request["id"].ToString());
                var ds = database.ExecuteQuery("select * from tbl_DailyQuestion where QuestionId =" + questionId);
                question = ds.Tables[0];
                btnCreate.Visible = false;
            }
            catch
            {
                questionId = 0;
                btnUpdate.Visible = false;
            }

            LiteralError.Text = "";
            LiteralSuccess.Text = "";
            if (!IsPostBack)
            {
                LoadData();
            }

        }

        void LoadData()
        {
            var ds = database.ExecuteQuery("select * from tbl_DailyCategory where IsActive =1");
            if (ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    ddlCategory.DataSource = dt;
                    ddlCategory.DataTextField = "Name";
                    ddlCategory.DataValueField = "CategoryId";
                    ddlCategory.DataBind();

                    if (questionId > 0)
                    {
                        for (int i = 0; i < ddlCategory.Items.Count; i++)
                        {
                            if (ddlCategory.Items[i].Value == question.Rows[0]["CategoryId"].ToString())
                                ddlCategory.Items[i].Selected = true;
                        }
                    }
                }

                if (questionId > 0)
                {
                    txtQuestion.Text = question.Rows[0]["Content"].ToString();
                    var dsAnswer = database.ExecuteQuery("select * from tbl_DailyAnswer where QuestionId =" + questionId);
                    if (dsAnswer.Tables.Count > 0)
                    {
                        var dtAnswer = dsAnswer.Tables[0];
                        if (dtAnswer.Rows.Count > 0)
                        {
                            txtAnswer1.Text = dtAnswer.Rows[0]["Content"].ToString();
                            RadioButton1.Checked = dtAnswer.Rows[0]["IsTrue"].ToString() == "1";
                        }
                        if (dtAnswer.Rows.Count > 1)
                        {
                            txtAnswer2.Text = dtAnswer.Rows[1]["Content"].ToString();
                            RadioButton2.Checked = dtAnswer.Rows[1]["IsTrue"].ToString() == "1";
                        }
                        if (dtAnswer.Rows.Count > 2)
                        {
                            txtAnswer3.Text = dtAnswer.Rows[2]["Content"].ToString();
                            RadioButton3.Checked = dtAnswer.Rows[2]["IsTrue"].ToString() == "1";
                        }
                        if (dtAnswer.Rows.Count > 3)
                        {
                            txtAnswer4.Text = dtAnswer.Rows[3]["Content"].ToString();
                            RadioButton4.Checked = dtAnswer.Rows[3]["IsTrue"].ToString() == "1";
                        }

                        if (dtAnswer.Rows.Count > 4)
                        {
                            txtAnswer5.Text = dtAnswer.Rows[4]["Content"].ToString();
                            RadioButton5.Checked = dtAnswer.Rows[4]["IsTrue"].ToString() == "1";
                        }
                        if (dtAnswer.Rows.Count > 5)
                        {
                            txtAnswer6.Text = dtAnswer.Rows[5]["Content"].ToString();
                            RadioButton6.Checked = dtAnswer.Rows[5]["IsTrue"].ToString() == "1";
                        }


                    }
                }
            }


        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {

            List<AnswerModel> list = new List<AnswerModel>();
            list.Add(new AnswerModel() { Content = txtAnswer1.Text.Trim(), IsTrue = RadioButton1.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer2.Text.Trim(), IsTrue = RadioButton2.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer3.Text.Trim(), IsTrue = RadioButton3.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer4.Text.Trim(), IsTrue = RadioButton4.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer5.Text.Trim(), IsTrue = RadioButton5.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer6.Text.Trim(), IsTrue = RadioButton6.Checked });
            //bo nhung dòng khong nhap data
            list = list.Where(c => c.Content.Length > 0).ToList();

            if (list.Where(c => c.IsTrue).Count() <= 0)
            {
                LiteralError.Text = "Chưa chọn đáp án đúng.";
                return;
            }
            string aa = questionId.ToString();
            //them cau hoi
            string sql = string.Format("INSERT INTO tbl_DailyQuestion (CategoryId,Content,CreatedDate,UpdatedDate,UpdatedBy) VALUES('{0}',N'{1}','{2}','{3}','{4}');SELECT SCOPE_IDENTITY()",
                ddlCategory.SelectedValue, txtQuestion.Text, DateTime.Now.ToString("MM/dd/yyyy"), DateTime.Now, UserInfo.UserID);
            //SqlConnection
            int id = ThuVien.FunctionsUtils.ConvertToInt(database.ExecuteScalar(sql).ToString(), 0);
            if (id > 0)
            {

                foreach (var item in list)
                {
                    string sqlAnswer = string.Format("INSERT INTO tbl_DailyAnswer (QuestionId,Content,IsTrue) VALUES('{0}',N'{1}','{2}')", id, item.Content, item.IsTrue ? 1 : 0);
                    database.ExecuteQuery(sqlAnswer);

                }
                LiteralSuccess.Text = "Thêm thành công. Hãy nhập câu hỏi tiếp theo";
                txtAnswer1.Text = txtAnswer2.Text = txtAnswer3.Text = txtAnswer4.Text = txtAnswer5.Text = txtAnswer6.Text = "";
                txtQuestion.Text = "";
            }

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            List<AnswerModel> list = new List<AnswerModel>();
            list.Add(new AnswerModel() { Content = txtAnswer1.Text.Trim(), IsTrue = RadioButton1.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer2.Text.Trim(), IsTrue = RadioButton2.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer3.Text.Trim(), IsTrue = RadioButton3.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer4.Text.Trim(), IsTrue = RadioButton4.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer5.Text.Trim(), IsTrue = RadioButton5.Checked });
            list.Add(new AnswerModel() { Content = txtAnswer6.Text.Trim(), IsTrue = RadioButton6.Checked });
            //bo nhung dòng khong nhap data
            list = list.Where(c => c.Content.Length > 0).ToList();

            if (list.Where(c => c.IsTrue).Count() <= 0)
            {
                LiteralError.Text = "Chưa chọn đáp án đúng.";
                return;
            }

            //sua cau hoi
            string sql = string.Format("UPDATE tbl_DailyQuestion SET CategoryId={0},Content=N'{1}',UpdatedDate='{2}',UpdatedBy='{3}' WHERE QuestionId={4}",
                ddlCategory.SelectedValue, txtQuestion.Text, DateTime.Now, UserInfo.UserID, questionId);
            //SqlConnection
            database.ExecuteQuery(sql);
            //lấy ra list id đáp án
            List<string> listDapAn = new List<string>();
            var ds = database.ExecuteQuery("SELECT * FROM tbl_DailyAnswer WHERE QuestionId=" + questionId);
            if (ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0];
                listDapAn = dt.AsEnumerable().Select(c => c.Field<int>("AnswerId").ToString()).ToList();
            }
            int count = list.Count;
            if (listDapAn.Count > count)
                count = listDapAn.Count();
            string sqlDapAn = "";
            for (int i = 0; i < count; i++)
            {
                if (listDapAn.Count() > i && list.Count() > i)//update
                {
                     sqlDapAn = string.Format("UPDATE tbl_DailyAnswer SET Content=N'{0}', IsTrue={1} WHERE AnswerId={2}", list[i].Content, list[i].IsTrue ? 1 : 0, listDapAn[i]);
                    database.ExecuteQuery(sqlDapAn);
                }
                else if (listDapAn.Count() <= i && list.Count() > i)//insert
                {
                    sqlDapAn = string.Format("INSERT INTO tbl_DailyAnswer (QuestionId,Content,IsTrue) VALUES('{0}',N'{1}','{2}')", questionId, list[i].Content, list[i].IsTrue ? 1 : 0);
                    database.ExecuteQuery(sqlDapAn);
                }
                else if (listDapAn.Count() > i && list.Count() <= i)//delete
                {
                    sqlDapAn = "DELETE tbl_DailyAnswer WHERE AnswerId="+listDapAn[i];
                    database.ExecuteQuery(sqlDapAn);
                }
            }

            ClosePopup(false);
            Response.Write("<script>parent.ReloadWindow();</script>");
        }
    }
}